<?php


namespace app\zhengmaotong\Controller;


use app\zhengmaotong\model\NavModel;
use app\zhengmaotong\validate\NavValidate;
use cmf\controller\AdminBaseController;

class NavController extends AdminBaseController
{
    public function index()
    {
        $keyword = input('keyword', '');
        $where = [];
        if ($keyword) {
            $where[] = ['title|id', 'like', '%' . $keyword . '%'];
        }
        $list =NavModel::order('list_order', 'desc')
            ->where($where)
            ->paginate(5);
        $this->assign('nav', $list);
        return $this->fetch();
    }
    //显示添加页面
    public function add()
    {
        return $this->fetch();
    }

    //添加的提交
    public function addPost()
    {
      //接收数据
        $data = input('post.');
        // 验证数据
        $validate = new NavValidate();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $nav = new NavModel();
        $nav->title = $data['title'];
        $nav->url = $data['url'];
        $nav->image = $data['image'];
        if ($nav->save()) {
                $this->success('添加成功', url('Nav/index'));
            } else {
                $this->error('添加失败');
            }
        }



    //显示编辑页面
    public function edit($id)
    {
        $nav =NavModel::find($id);
        if (!$nav) {
            $this->error('导航不存在');
        }
        $this->assign('nav', $nav);
        return $this->fetch('edit');
    }

    //添加的提交
    public function editPost()
    {
        //接收数据
        $data = input('post.');
        //先查询数据
        $nav = NavModel::find($data['id']);
        if(!$nav){
            $this->error('未查询到数据');
        }
        $nav->title = $data['title'];
        $nav->url = $data['url'];
        $nav->image = $data['image'];
        //然后入库
        if ($nav->save()) {
            $this->success('保存成功','Nav/index');
        } else {
            $this->success('保存失败');
        }

    }
    public function del()
    {
        $id = input('id/d');
        $nav = NavModel::destroy($id);
        if ($nav) {
            $this->success('删除成功','Nav/index');
        } else {
            $this->success('删除失败');
        }
    }
    public function order()
    {

        parent::listOrders(new NavModel());
        $this->success('排序成功');
    }
}